package com.sy.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sy.dto.StuInfo;
import com.sy.dto.StudentMagTable;
import com.sy.dto.Table;
import com.sy.entity.*;
import com.sy.exception.BusinessException;
import com.sy.service.HomeworkService;
import com.sy.service.StudentService;
import com.sy.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static com.sy.constant.RegConstant.PHONE_REGEX;
import static com.sy.constant.RegConstant.STRONG_PWD_REGEX;
import static org.springframework.http.HttpStatus.BAD_REQUEST;

@Service
public class StudentServiceImpl extends BaseServiceImpl implements StudentService {

    @Override
    public StuInfo getStuInfo(String id) {
        if(StringUtils.isBlank(id)){
            buildError(BAD_REQUEST,"ID不能为空！");
        }
        return studentMapper.getStuInfoById(id);
    }

    @Override
    public boolean updateStuInfo(StuInfoVo stuInfoVo) {
        String id = stuInfoVo.getId();
        String name = stuInfoVo.getName();
        String phone = stuInfoVo.getPhone();
        if( StringUtils.isBlank(id)){
            buildError(BAD_REQUEST,"ID不能为空！");
        }

        if (!phone.matches(PHONE_REGEX)) {
            buildError(BAD_REQUEST,"手机号格式不合法");
        }

        studentMapper.updateStuInfo(stuInfoVo);
        return true;
    }

    @Override
    public Page<HomeWorkMessage> getAllNotDoHomeWork(String id, String keywords, Integer page, Integer limit,Integer classId) {
        PageHelper.startPage(page, limit);
        Page<HomeWorkMessage> homeWorkMessage =(Page<HomeWorkMessage>) studentMapper.getAllNotDoHomeWork(id,keywords,classId);
        return homeWorkMessage;
    }

    @Override
    public List<ChoiceQuestion> getAllQuestionsByHomeWorkId(String id) {
        return studentMapper.getAllQuestionsByHomeWorkId(id);
    }

    @Override
    public ShortQuestion getStudentNotDoHomeWorkShortQuestion(String id) {
       return  studentMapper.getStudentNotDoHomeWorkShortQuestion(id);
    }

    @Override
    public Student getStudentsMessage(String id) {
        return studentMapper.getStudentsMessage(id);
    }

    @Override
    public  Page<HomeWorkMessage> getAllHaveDoHomeWork(String id, String keywords, Integer page, Integer limit, Integer classId) {
        PageHelper.startPage(page, limit);
        Page<HomeWorkMessage> homeWorkMessage =(Page<HomeWorkMessage>) studentMapper.getAllHaveDoHomeWork(id,keywords,classId);
        return homeWorkMessage;
    }

    @Override
    public Page<StudentShowScore> getStudentGradeById(String id, String keywords, Integer page, Integer limit, Integer condition) {
        PageHelper.startPage(page, limit);
        Page<StudentShowScore> studentGradeById =(Page<StudentShowScore>) studentMapper.getStudentGradeById(id, condition, keywords);
        return studentGradeById;
    }

    @Override
    public Page<StudentDownloadCourseware> getTeacherUploadFile(Integer teacherId, String keywords, Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        Page<StudentDownloadCourseware> teacherUploadFile =(Page<StudentDownloadCourseware>) studentMapper.getTeacherUploadFile(teacherId, keywords);

        return teacherUploadFile;
    }

    @Override
    public ClassMsg selectTeacherByClassId(Integer classId) {
        return studentMapper.selectTeacherByClassId(classId);
    }

    @Override
    public boolean insertShortAnswer(Integer studentId, Integer shortquestionId, String answer,Integer homeworkId) {
        return studentMapper.insertShortAnswer(studentId, shortquestionId, answer,homeworkId);

    }

    @Override
    public boolean insertChoiceAnswer(Integer studentId, Integer choicequestionId, Integer choiceId, Integer homeworkId) {
        return studentMapper.insertChoiceAnswer(studentId, choicequestionId, choiceId, homeworkId);
    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED
            , rollbackFor = {BusinessException.class})
    public void insertHomeWorkAllAnswer(StudentSubmitAnswer studentSubmitAnswer, Integer studentId) {
        try {

//            作业的id
             Integer homeworkId = studentSubmitAnswer.getHomeworkId();
//             选择题的所有答案id和题目的id集合
             List<Answers> answer = studentSubmitAnswer.getAnswers();
//           简答题的答案和id
            ShortAnswer shortAnswer = studentSubmitAnswer.getShortAnswer();
            for (int i = 0; i < answer.size(); i++) {
                System.out.println("---------------------");
                System.out.println(answer.size());
                System.out.println("---------------------");
//                拿到选择答案的id
                 Integer choiceId = answer.get(i).getChoiceId();
//                 拿到选择题目的id
                Integer themeId = answer.get(i).getChoicequestionId();
                studentMapper.insertChoiceAnswer(studentId,themeId,choiceId,homeworkId);
            }
//                  简答题的答案内容
                    String content = shortAnswer.getAnswer();
//                    简答题答案id
                   Integer id = shortAnswer.getShortquestionId();

            studentMapper.insertShortAnswer(studentId,id,content,homeworkId);


        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            throw new BusinessException(HttpStatus.NOT_FOUND, e.getMessage());

        }


    }

    @Override
    public List<Answers> selectSubmitChoiceAnswer(Integer homeworkId,Integer studentId) {
        return studentMapper.selectSubmitChoiceAnswer(homeworkId,studentId);
    }

    @Override
    public ShortAnswer selectSubmitShortAnswer(Integer homeworkId,Integer studentId) {
        return studentMapper.selectSubmitShortAnswer(homeworkId,studentId);
    }

    @Override
    public boolean updateChoiceAnswer(Integer choiceId, Integer homeworkId, Integer choicequestionId,Integer studentId){
       return studentMapper.updateChoiceAnswer(choiceId,homeworkId,choicequestionId,studentId);
    }

    @Override
    public boolean updateShortQuestionAnswer(String answer, Integer homeworkId, Integer shortquestionId,Integer studentId) {
        return studentMapper.updateShortQuestionAnswer(answer,homeworkId,shortquestionId,studentId);
    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED
            , rollbackFor = {BusinessException.class})
    public void updateAllAnswer(StudentSubmitAnswer studentSubmitAnswer, Integer studentId) {
        try {
//            作业的id
            Integer homeworkId = studentSubmitAnswer.getHomeworkId();
//             选择题的所有答案id和题目的id集合
            List<Answers> answer = studentSubmitAnswer.getAnswers();
//           简答题的答案和id
            ShortAnswer shortAnswer = studentSubmitAnswer.getShortAnswer();

            for (int i = 0; i < answer.size(); i++) {
//                拿到选择答案的id
                Integer choiceId = answer.get(i).getChoiceId();
//                 拿到选择题目的id
                Integer themeId = answer.get(i).getChoicequestionId();
                studentMapper.updateChoiceAnswer(choiceId,homeworkId,themeId,studentId);
            }
//            简答题的答案内容
            String content = shortAnswer.getAnswer();
//                    简答题答案id
            Integer id = shortAnswer.getShortquestionId();
            studentMapper.updateShortQuestionAnswer(content,homeworkId,id,studentId);

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            throw new BusinessException(HttpStatus.NOT_FOUND, e.getMessage());

        }
    }



    @Override
    public Page<StudentMagTable> getStudentsNoSubmit(Integer homeworkId,Integer page,Integer limit) {
        //根据作业id获得班级id
        Homework homework = homeworkMapper.getHomeworkById(homeworkId);
        //班级id
        Integer classId = homework.getClassId();
        //根据班级id获取学生的id列表
        List<Integer> studentsIdList = studentMapper.getStudentsIdListByClassId(classId);
        //根据作业id去查照已提交作业的学生的id列表
        List<Integer> studentIdListForSubmit = studentMapper.getStudentIdListForSubmit(homeworkId);
        //获取班级中未提交作业的学生id
        List<Integer>  studentsIdListForNoSubmit =studentsIdList;
        studentsIdListForNoSubmit.removeAll(studentIdListForSubmit);
        if(studentsIdListForNoSubmit.isEmpty()){
            throw new BusinessException(HttpStatus.NOT_FOUND,"没有学生未提交");
        }
        //根据未提交作业的学生id获得学生列表信息
        PageHelper.startPage(page,limit);
        Page<StudentMagTable> studentsByIdList =(Page<StudentMagTable>) studentMapper.getStudentsByIdList(studentsIdListForNoSubmit);
        return studentsByIdList;

    }

    @Override
    public Student selectStudentsOwnMessage(Integer id) {
        return studentMapper.selectStudentsOwnMessage(id);
    }

    @Override
    public ClassMsg selectClassMessageByClassId(Integer classId) {
        return studentMapper.selectClassMessageByClassId(classId);
    }

    @Override
    public boolean updateStudentNewMessage(String name, String gender, String phone, Integer id) {
        String s = String.valueOf(phone);
//       对传入得手机号进行校验
        if (!s.matches(PHONE_REGEX)) {
            buildError(BAD_REQUEST, "手机号格式不合法，请重新输入手机号");
        }
        return studentMapper.updateStudentNewMessage(name, gender, s, id);


    }

    @Override
    public boolean updateStudentPassword(String oldPassword,Integer id,String  confirmNewPassword,String newPassword) {
//       对传入的参数进行验证
       Student student = studentMapper.selectStudentsOwnMessage(id);
         String password1 = student.getPassword();
         if(!oldPassword.equals(password1)){
             buildError(BAD_REQUEST, "请输入正确的原来的密码");
         }
         if(!oldPassword.matches(STRONG_PWD_REGEX)){
             buildError(BAD_REQUEST, "密码中必须包含字母、数字(8-10位");
         }
         if(!confirmNewPassword.matches(STRONG_PWD_REGEX)){
             buildError(BAD_REQUEST, "密码中必须包含字母、数字(8-10位");
         }if(!newPassword.matches(STRONG_PWD_REGEX)){
            buildError(BAD_REQUEST, "密码中必须包含字母、数字(8-10位");
        }
         if(password1.equals(newPassword)){
             buildError(BAD_REQUEST, "修改密码不能与之前密码一致");
         }

         if(!confirmNewPassword.equals(newPassword)){
             buildError(BAD_REQUEST, "两次输入的密码不一致");
         }
        return studentMapper.updateStudentPassword(newPassword, id);
    }

    @Override
    public Homework selectHomeWorkIdByTitle(String title) {
        return studentMapper.selectHomeWorkIdByTitle(title);
    }

    @Override
    public List<ChoiceAnswer> selectAllChoiceIdByHomeworkId(Integer homeworkId) {
        return studentMapper.selectAllChoiceIdByHomeworkId(homeworkId);
    }

    @Override
    public Choice selectTrueChoiceAnswerByChoiceId(Integer choiceQuestionId) {
        return studentMapper.selectTrueChoiceAnswerByChoiceId(choiceQuestionId);
    }
}
